package net.ojbk.study.twobox.web.handlers;

import net.ojbk.study.twobox.beans.constraint.Constraint;
import net.ojbk.study.twobox.service.SupperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/4/11
 * Time: 18:30
 * Description: No Description
 */
public class SupperController<T> {
    @Autowired
    protected SupperService<T> service;

    // 增删改查
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<Object> addOne(HttpSession session, @Validated @RequestBody T obj, BindingResult br) throws Exception {
        service.addOne(obj, br);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Object> deleteOne(HttpSession session, @PathVariable("id") Integer id) throws Exception {
        service.deleteOne(id);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseEntity<Object> updateOne(HttpSession session, @Validated @RequestBody T obj, BindingResult br) throws Exception {
        service.updateOne(obj, br);
        return new ResponseEntity<Object>(HttpStatus.OK);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseEntity<Object> getList(HttpSession session, Integer currentPage) throws Exception {
        return new ResponseEntity<Object>(service.getAll(currentPage), HttpStatus.OK);
    }

    // 条件分页查询
    @RequestMapping(value = "eligible", method = RequestMethod.POST)
    public ResponseEntity<Object> getListByConstraint(HttpSession session, @RequestBody Constraint<T> constraint) throws Exception {
        // {"currentPage": 1, "constraint":{"depname": "财务部"}}
        return new ResponseEntity<>(service.getAllByConstraint(constraint), HttpStatus.OK);
    }

    // 获取form
    // PostForm
    @RequestMapping(value = "form/post", method = RequestMethod.GET)
    public ResponseEntity<Object> getPostForm(HttpSession session) throws Exception {
        return new ResponseEntity<>(service.getPostForm(), HttpStatus.OK);
    }

    // queryForm
    @RequestMapping(value = "form/query", method = RequestMethod.GET)
    public ResponseEntity<Object> getQueryForm(HttpSession session) throws Exception {
        return new ResponseEntity<>(service.getQueryForm(), HttpStatus.OK);
    }
}
